const db = wx.cloud.database();
const app = getApp();
const util = require('../../utils/util.js');

Page({
    data:{
        nickName: '',//保存用户昵称
        avatarUrl: ''//保存用户头像
    },

    onLoad() {
        console.log('昵称:',nickName)
    },
    //用户登录授权
    getUserInfo(e) {
        wx.cloud.callFunction({
            name:'wechatRun',
            complete: res=>{
                const openid = res.result.openid
                db.collection('user').where({
                    _openid: openid
                }).get()
                .then(res=>{
                    console.log(res)
                    //确保数据库中只有唯一一条数据
                    if(res.data=='') {
                        console.log('授权登录成功')
                        this.setData({
                            isFirstLogin: 1
                        })
                        //跳转到主界面
                        wx.navigateTo({
                          url: '/pages/profile/profile',
                        })
                        db.collection('user').add({
                            data:{
                                nickName: e.detail.userInfo.nickName,
                                avatarUrl: e.detail.userInfo.avatarUrl,
                                time: util.formatTime(new Date()),
                            }
                        })
                    } else {
                        console.log('已经登录过不用授权')
                        wx.navigateTo({
                          url: '/pages/profile/profile',//登录成功要跳转到的页面
                        })
                    }
                })
            }
        })
        this.setData({
            nickName: e.detail.userInfo.nickName,
            avatarUrl: e.detail.userInfo.avatarUrl
        })
    }
})